package routers

import (
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"github.com/dchest/captcha"
	"quickstart/controllers/api"
	"quickstart/controllers/home"
	"quickstart/global/response"
	"quickstart/middleware"
	"quickstart/services"
)

func init() {
	//首页
	beego.Router("/", &home.HomeController{}, "get:Index")

	//登录、注册、退出
	beego.Router("/Login", &home.AccountController{}, "get,post:Login")
	beego.Router("/Register", &home.AccountController{}, "get,post:Register")
	beego.Router("/Logout", &home.AccountController{}, "get:Logout")

	//验证码
	beego.Router("/account/refresh_captcha", &home.AccountController{}, "post:RefreshCaptcha")
	//二维码输出
	beego.Handler("/account/captcha/*.png", captcha.Server(240, 80))

	islogin := beego.NewNamespace("/new",
		beego.NSBefore(AuthFilter), //直接使用中间件
		beego.NSRouter("/index", &home.NewController{}, "get:Index"),
	)
	//个人中心
	member := beego.NewNamespace("/member",
		beego.NSRouter("/index", &home.MemberController{}, "get:Index"),
	)

	//接口
	middleware.CorsMiddle("/api/*")
	api := beego.NewNamespace("/api",
		beego.NSRouter("/index", &api.IndexController{}, "get:Index"),
	)
	beego.AddNamespace(api, member, islogin)
}

//权限验证过滤器
func AuthFilter(ctx *context.Context) {
	token := ctx.GetCookie("token")
	if token != "" {
		sa := services.AuthService{}
		if !sa.Logined {
			if ctx.Input.IsPost() {
				response.SuccessWithMessage("请登录", ctx)
			} else {
				ctx.Redirect(302, "/Login")
			}
		}
	}
}
